import { _decorator, assetManager, Color, ImageAsset, Label, Node, Sprite, SpriteFrame, Texture2D, UIOpacity, UITransform, Vec3, view } from 'cc';
import { BaseUI } from '../../framework/base/BaseUI';
import List from '../../framework/commont/list/List';
import { SDKMgr } from '../../framework/manager/SDKMgr';
import { WXGameService } from '../../sdk/WXGameService';
import { GameDef } from '../gameLogic/GameDef';
import { PlayerMgr } from '../manager/PlayerMgr';
const { ccclass, property } = _decorator;

@ccclass('UIRank')
export class UIRank extends BaseUI {

    @property({ type: [SpriteFrame] })
    topIcons: SpriteFrame[] = [];
    scrollView: Node = null;
    friendListView: Node = null;
    root: Node = null;
    list: List = null;
    rankData: rankData[] = [];
    rankData1: rankData[] = null;
    userInfoButton: Node = null;
    btnShareAll: Node = null;
    titleLabel1: Label = null;
    titleLabel2: Label = null;
    currAllData: rankData[] = [];
    rankKey: string = "zsxc-nationalKey";
    async start() {
        this.root = this.node.getChildByName("root");
        this.scrollView = this.root.getChildByName("ScrollView");
        this.friendListView = this.root.getChildByName("friendListView");
        this.userInfoButton = this.root.getChildByName("userInfoButton")
        this.btnShareAll = this.root.getChildByName("btnShareAll")
        this.titleLabel1 = this.root.getChildByName("text-001").getComponent(Label)
        this.titleLabel2 = this.root.getChildByName("text-002").getComponent(Label)
        this.list = this.scrollView.getComponent(List);
        this.rankData = this.rankData?this.rankData:await this.getRankDataInServer();
        this.list.arrayData = this.rankData;
        this.addNodeClickEvent()
        this.friendListView.active = true
        this.scrollView.active = false
        this.btnShareAll.active = true
        this.userInfoButton.active = false
        // this.titleLabel1.string = '玩家/通关关卡'
        // this.titleLabel2.string = '好友分享'
        this.getUserData((info) => {
            WXGameService.submitWorldScore(
                PlayerMgr.instance.appid, PlayerMgr.instance.uid, this.rankKey, PlayerMgr.instance.getUserData().gameScore,
                JSON.stringify({ userName: info.nickName, avatarUrl: info.avatarUrl }),
            ).then((isSucc) => {
                if (isSucc) {
                    console.log("提交成功")
                } else {
                    console.log("提交失败")
                }
            })
            // this.userInfoButton.active = fa
            // if(info.nickName){
            //     this.userInfoButton.active = true
            // }
        })
        this.findChilds("dqShowText").getComponent(Label).string = "地区："+GameDef.instance.cityName;
        this.onTabFriend()

    }
    getBtnInfo(rect) {
        let screenSize = view.getVisibleSize();
        let systemInfo = wx.getSystemInfoSync();
        //当前sdk版本
        let screenWidth = systemInfo.screenWidth;
        let screenHeight = systemInfo.screenHeight;
        // 否则，先通过 wx.createUserInfoButton 接口发起授权
        // let leftPos = (rect.x - (rect.width / 2)) * screenWidth / screenSize.width;
        let leftPos = (rect.x) * screenWidth / screenSize.width;// - (rect.width) / 64
        console.log("leftPos：", leftPos)
        // let topPos = ((screenSize.height - rect.y) - (rect.height / 2)) * screenHeight / screenSize.height;
        let topPos = ((screenSize.height - rect.y) - (rect.height)) * screenHeight / screenSize.height;
        let trueWidth = rect.width * screenWidth / screenSize.width;
        let trueHeight = rect.height * screenHeight / screenSize.height;
        console.log("systemInfo：", screenSize, screenWidth, screenHeight, leftPos, topPos, trueWidth, trueHeight)
        return { leftPos: leftPos, topPos: topPos, trueWidth: trueWidth, trueHeight: trueHeight }
    }
    userButton: wx.UserInfoButton = null
    getUserData(callback?: Function) {
        if (!window['wx']) {

            callback && callback({ avatarUrl: "", nickName: "未知" })
            return
        }
        wx.getSetting({
            success: (res) => {
                if (res.authSetting['scope.userInfo']) {
                    // 已经授权，可以直接调用 getUserInfo 获取头像昵称
                    wx.getUserInfo({
                        success: (res) => {
                            console.log("玩家信息", res.userInfo)
                            this.onSetUserData(res.userInfo)
                            callback && callback(res.userInfo)
                            this.userInfoButton.active = false
                        }
                    })
                } else {
                    // 未授权，需要调用 wx.authorize 接口发起授权
                    wx.authorize({
                        scope: 'scope.userInfo',
                        success: () => {
                            wx.getUserInfo({
                                success: (res) => {
                                    console.log("玩家信息", res.userInfo)
                                    this.onSetUserData(res.userInfo)
                                    callback && callback(res.userInfo)
                                    this.userInfoButton.active = false
                                }
                            })
                        },
                        fail: () => {
                            this.userInfoButton.active = true
                            let info = this.getBtnInfo(this.userInfoButton.getComponent(UITransform).getBoundingBoxToWorld())
                            this.userButton = wx.createUserInfoButton({
                                type: 'text',
                                text: '',
                                style: {
                                    left: info.leftPos,
                                    top: info.topPos,
                                    width: info.trueWidth,
                                    height: info.trueHeight,
                                    lineHeight: info.trueHeight,
                                    // backgroundColor: '#d9bdf5',
                                    color: '#3b184e',
                                    // borderColor: '#3b184e',
                                    borderWidth: 3,
                                    textAlign: 'center',
                                    fontSize: 16,
                                    borderRadius: 4
                                }
                            })
                            this.userButton.onTap((res) => {
                                // 用户同意授权后回调，通过回调可获取用户头像昵称信息
                                console.log(res)
                                if (res.userInfo) {
                                    this.onSetUserData(res.userInfo)
                                    callback && callback(res.userInfo)
                                    this.userInfoButton.active = false
                                    this.userButton.destroy()
                                    this.userButton = null
                                } else {

                                    this.userInfoButton.active = true
                                    let data = localStorage.getItem("userInfo")
                                    if (data) {
                                        let _data = JSON.parse(data)
                                        callback && callback({ avatarUrl: _data.avatarUrl, nickName: _data.nickname })
                                        console.log("读取缓存")
                                    } else {
                                        callback && callback({ avatarUrl: "", nickName: "未知" })
                                        console.log("读取缓存失败，重新定义")
                                    }
                                    console.warn("用户拒绝授权")
                                }
                            })
                        }
                    })
                }
            }
        })

    }
    private _userInfo: wx.UserInfo;
    onSetUserData(data: wx.UserInfo) {
        this._userInfo = data
        localStorage.setItem("userInfo", JSON.stringify(data))
        this.openDataContent()
        this.getRank()
    }

    onshareAppMessage() {
        console.log("分享")
        SDKMgr.getInstance().share()
    }

    addNodeClickEvent() {
        this.root.getChildByName("box").getChildByName('tabItem1').on('click', this.onNational, this)
        this.root.getChildByName("box").getChildByName('tabItem2').on('click', this.onTabRegional, this)
        this.root.getChildByName("box").getChildByName('tabItem3').on('click', this.onTabFriend, this)
        this.root.getChildByName("btnClose").on('click', this.onCloseUI, this)
    }
    onCloseUI() {
        this.closeUI()
        this.userButton && this.userButton.hide()
        this.hideRank()
    }

    onTabFriend() {
        console.warn("好友")
        this.friendListView.active = true
        this.scrollView.active = false
        this.btnShareAll.active = true

        this.selectTabState(2)
        this.root.getChildByName("box").getChildByName("tiaozhuank").position = new Vec3(142, 0, 0)
        this.userButton && this.userButton.show()
        this.userButton && (this.friendListView.active = true, this.userInfoButton.active = true)
        this.root.getChildByName("mySelfItem").active = false
        console.log("this.userInfoButton.", this.userInfoButton)
        this.getRank()
    }
    async onNational() {
        console.warn("全国")
      
        this.hideOther();
        this.selectTabState(0)

        this.root.getChildByName("box").getChildByName("tiaozhuank").position = new Vec3(-142, 0, 0)
        this.list.arrayData = await this.getRankDataInServer() || []
        for (let k in this.list.arrayData) {
            if (this.list.arrayData[k].uid == PlayerMgr.instance.uid) {
                this.onItemUpData(this.root.getChildByName("mySelfItem"), Number(k), this.list.arrayData[k])
            }
        }
        this.root.getChildByName("mySelfItem").active = true
        //    this.list.updateAll()
    }
    //地区排行 onTabRegional
    async onTabRegional() {
        console.warn("地区")
      
        this.hideOther()
        this.root.getChildByName("box").getChildByName("tiaozhuank").position = new Vec3(0, 0, 0)
        this.selectTabState(1)
        this.list.arrayData= this.rankData1?this.rankData1:await this.getProvinceRankDataInServer();
        for (let k in this.list.arrayData) {
            if (this.list.arrayData[k].uid == PlayerMgr.instance.uid) {
                this.onItemUpData(this.root.getChildByName("mySelfItem"), Number(k), this.list.arrayData[k])
            }
        }
        this.list.updateAll()
        this.root.getChildByName("mySelfItem").active = true
        console.warn("地区排行", this.rankData1)
    }
    hideOther(){
        this.scrollView.active = true
        this.friendListView.active = false;
        this.btnShareAll.active = false
        this.userInfoButton.active = false
        // this.hideRank()
        this.userButton && this.userButton.hide()
    }

    async getRankDataInServer() {
        let data = await WXGameService.getWorldRankData(PlayerMgr.instance.appid, PlayerMgr.instance.uid, this.rankKey, null, 99) as any
        this.rankData = data.data.data
        console.log("data")
        return this.rankData
    }
    async getProvinceRankDataInServer() {
        let data = await WXGameService.getWorldRankData(PlayerMgr.instance.appid, PlayerMgr.instance.uid, GameDef.instance.proCode, null, 99) as any
        return data.data.data
    }
    //切换菜单状态
    private selectTabState(index: number) {
        let arr = [
            this.root.getChildByName("qgText").getComponent(Label),
            this.root.getChildByName("dqText").getComponent(Label),
            this.root.getChildByName("hyText").getComponent(Label)
        ];
        for (let i = 0; i < arr.length; i++) {
            arr[i].color = new Color().fromHEX("DF8351")
            arr[i].enableOutline = false;
        }
        arr[index].color = new Color().fromHEX("ffffff")
        arr[index].enableOutline = true;
    }
    onItemUpData(item: any, index: number, data: any) {
        let tanIcon = item.getChildByName("tanIcon")
        let avatar = item.getChildByName("touxiang")
        let nameText = item.getChildByName("nameText")
        let levelText = item.getChildByName("levelText")
        let topText = item.getChildByName("topText")
        data = data ? data : this.rankData[index]
        if (!data) {
            return
        }
        let dataInfo: any = {}
        if (data.info == "null" || data.info == '[object Object]') {
            data.info = {
                name: "我的名字七个字",
                avatarUrl: "",
            }
            dataInfo = data.info
        } else {
            dataInfo = JSON.parse(data.info)
        }
        // console.warn("dataInfo", dataInfo)

        if (index > 2) {
            tanIcon.getComponent(UIOpacity).opacity = 0;
            topText.getComponent(Label).string = index + ""

        } else {
            tanIcon.getComponent(UIOpacity).opacity = 255;
            topText.getComponent(Label).string = "";

            tanIcon.getComponent(Sprite).spriteFrame = this.topIcons[index]
        }
        if (dataInfo && dataInfo.avatarUrl != "" || dataInfo && !!dataInfo.avatarUrl) {
            assetManager.loadRemote(dataInfo.avatarUrl, { ext: '.png' }, (err, asset: ImageAsset) => {
                console.log("加载图片成功", asset)
                let sp: SpriteFrame = new SpriteFrame();
                let tx: Texture2D = new Texture2D();
                tx.image = asset;
                sp.texture = tx;
                avatar.getComponent(Sprite).spriteFrame = sp;
            })
        }
        // this.loadRemoteSpriteFrame(dataInfo.avatarUrl, (spriteFrame: SpriteFrame) => {
        //     //  avatar.getComponent(SpriteFrame) = spriteFrame;
        //     console.log("加载图片成功", spriteFrame)
        // }, true)
        nameText.getComponent(Label).string = dataInfo.userName;
        levelText.getComponent(Label).string = data.score.toString();
        // console.log("onItemUpData", data, item, index);
    }

    /*************************************** 好友开放************************************************ */
    openDataContent() {
        this.setUserCloudStorage()
    }

    setUserCloudStorage() {
        if (!window['wx']) {
            return
        }
        window['wx'].setUserCloudStorage({
            KVDataList: [{
                key: 'rankData', value: JSON.stringify({
                    score: PlayerMgr.instance.getUserData().gameScore
                })
            }],
            success: (res) => {
                console.log("存储成功", res)
                this.setScore(res)
            },
            fail: (res) => {
                console.log("存储失败", res)
            }
        })
    }
    /**
     * 显示排行榜
     * @param res
     */
    setScore(data: any) {
        if (window['wx']) {
            window['wx'].postMessage({
                event: 'setScore',
                data: data
            });
        }
    }
    /**
     * 获取排行榜
     * @param res
     */
    getRank() {
        if(!this._userInfo){

            return;
        }
        if (window['wx']) {
            window['wx'].postMessage({
                event: 'getRank',
                userInfo: this._userInfo
            })
        }
    }
    hideRank() {
        if (window['wx']) {
            window['wx'].postMessage({
                event: 'hideRank',
            })
        }
    }
}


interface rankData {
    info: {
        name: string,
        avatarUrl: string,
    },
    score: number,
}